/**
 * @projectName: project02bywdmtz
 * @package: com.cskaoyan.service
 * @className: WxGoodsServiceImpl
 * @author: 冉夏
 * @description: TODO
 * @date: 2022/12/31 22:49
 * @version: 1.8
 */

package com.cskaoyan.service;

import com.cskaoyan.bean.*;

import com.cskaoyan.bean.bo.WxCommentBo;
import com.cskaoyan.bean.bo.WxGoodsSpecificationBo;
import com.cskaoyan.bean.bo.WxTopicGoodsDetailBo;

import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.WxCategoryDataVo;
import com.cskaoyan.bean.vo.WxCategoryVo;
import com.cskaoyan.bean.vo.WxGoodsDetailVo;
import com.cskaoyan.bean.vo.WxSearchGoodsVo;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;


import java.util.ArrayList;
import javax.annotation.Resource;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/*
 * 查询当前关键字对应的商品,然后显示商品所在的大目录,显示在顶部
 * 用于分类显示商品,根据用户选择的分类信息,显示不同的商品内容
 * 逻辑:根据传递来的
 * 添加记录  只要搜索了就有记录
 *
 * */


@Service
public class WxGoodsServiceImpl implements WxGoodsService {

    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketCategoryMapper categoryMapper;
    //历史记录的添加
    @Autowired
    MarketSearchHistoryMapper historyMapper;

    @Resource
    MarketGoodsMapper marketGoodsMapper;


    /*
     *不要问我为什么这么写 我是傻逼 我也不知道我在写什么 功能对了能跑起来就可以
     * 我不想改了 也不想重写
     *  给出关键字后模糊查询商品信息
     * 给出brandsid查询商品信息
     * */
    @Override
    public WxSearchGoodsVo getGoodsInfoBySearch(MarketGoods goodsSearcherBo) {
        //======================================历史记录添加功能=========================================================
        //在这里插入搜索的历史记录信息
        //如果存在的话就修改时间  新添加的记录应该在最前面显示且如果再一次访问的话,就修改访问时间
        //遍历历史记录数据库 查询当前关键字是否在数据库内,如果在就更新时间,不在的话就添加记录
        //查询历史记录数据库
        MarketSearchHistoryExample historyExample = new MarketSearchHistoryExample();
        if(goodsSearcherBo.getKeyword()!=null){
            //拿去当前用户的session
            Subject subject = SecurityUtils.getSubject();
            MarketUser principal = (MarketUser) subject.getPrincipal();
            historyExample.createCriteria().andUserIdEqualTo(principal.getId()).andKeywordLike(goodsSearcherBo.getKeyword());
            //获得历史记录的数据集合
            List<MarketSearchHistory> searchHistories = historyMapper.selectByExample(historyExample);
            MarketSearchHistory marketSearchHistory = new MarketSearchHistory();
            //获取当前时间
            long currentTimeMillis = System.currentTimeMillis();
            //空的话添加记录
            if(searchHistories.isEmpty()){
                marketSearchHistory.setKeyword(goodsSearcherBo.getKeyword());
                marketSearchHistory.setDeleted(false);
                marketSearchHistory.setFrom("wxApp");
                marketSearchHistory.setUserId(principal.getId());
                //从共享域内部取出用户id
                marketSearchHistory.setUserId(principal.getId());
                marketSearchHistory.setAddTime(new Date(currentTimeMillis));
                marketSearchHistory.setUpdateTime(new Date(currentTimeMillis));
                //没有这条记录的时候 插入记录
                historyMapper.insertSelective(marketSearchHistory);
            }else {
                //不是空的话看数据库内是否有这个记录
                for (MarketSearchHistory searchHistory : searchHistories) {
                    if(searchHistory.getKeyword().equals(goodsSearcherBo.getKeyword())){
                        //如果有这个记录的话就更新当前记录的时间且修改状态码为1
                        marketSearchHistory.setUpdateTime(new Date(currentTimeMillis));
                        marketSearchHistory.setId(searchHistory.getId());
                        marketSearchHistory.setUserId(principal.getId());
                        marketSearchHistory.setDeleted(false);
                        //仅修改更新时间数据
                        historyMapper.updateByPrimaryKeySelective(marketSearchHistory);
                    }else {
                        //如果不包含的话 就插入数据
                        marketSearchHistory.setKeyword(goodsSearcherBo.getKeyword());
                        marketSearchHistory.setDeleted(false);
                        marketSearchHistory.setFrom("wxApp");
                        //从共享域内部取出用户id
                        marketSearchHistory.setUserId(principal.getId());
                        marketSearchHistory.setAddTime(new Date(currentTimeMillis));
                        marketSearchHistory.setUpdateTime(new Date(currentTimeMillis));
                        //没有这条记录的时候 插入记录
                        historyMapper.insertSelective(marketSearchHistory);
                    }
                }
            }
        }
//======================================商品显示功能=========================================================
        //创建要返回的对象
        WxSearchGoodsVo wxSearchGoodsVo = new WxSearchGoodsVo();
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        List<MarketCategory> categoryList = new LinkedList<>();
        List<MarketGoods> goodsList;
        //查询出包含这个关键字的语句
        List<WxTopicGoodsDetailBo> goodsDetailBos = new LinkedList<>();
        //由于这里的条件不同,需要返回的二级目录也不相同 0的时候返回所有,不是0的时候返回指定目录
        //搜索接口条件  显示全部商品
        if(goodsSearcherBo.getBrandId()==null&&goodsSearcherBo.getCategoryId()!=null){
            if (goodsSearcherBo.getCategoryId() == 0&&goodsSearcherBo.getKeyword()!=null) {
                //先根据传递过来的关键字查询出所有包含这个关键字的商品
                goodsExample.createCriteria().andNameLike("%" + goodsSearcherBo.getKeyword() + "%");
                goodsExample.setOrderByClause(goodsSearcherBo.getSort() + " " + goodsSearcherBo.getOrder());
                goodsList = goodsMapper.selectByExample(goodsExample);
                //搜索接口  第二种条件 指定id
                //如果是null的话 只查询category对应的商品
            } else if(goodsSearcherBo.getKeyword()==null){
                //如果不是0的话返回的是当前分类下的商品以及当前目录 且不按模糊查询
                goodsExample.clear();
                goodsExample.createCriteria().andCategoryIdEqualTo(goodsSearcherBo.getCategoryId());
                goodsList = goodsMapper.selectByExample(goodsExample);
            }else {
                //如果不是0的话返回的是当前分类下的商品以及当前目录
                goodsExample.clear();
                goodsExample.setOrderByClause(goodsSearcherBo.getSort() + " " + goodsSearcherBo.getOrder());
                goodsExample.createCriteria().andNameLike("%" + goodsSearcherBo.getKeyword() + "%")
                        .andCategoryIdEqualTo(goodsSearcherBo.getCategoryId());
                goodsList = goodsMapper.selectByExample(goodsExample);
            }
            //如果不是搜索接口的话
        }else{
            goodsExample.clear();
            goodsExample.createCriteria().andBrandIdEqualTo(goodsSearcherBo.getBrandId());
            goodsList = goodsMapper.selectByExample(goodsExample);
        }

        //需要新加排序条件
        List<MarketGoods> goodsList1 = new LinkedList<>();
        if(goodsSearcherBo.getBrandId()==null&&goodsSearcherBo.getCategoryId()==null){
            goodsExample.clear();
            goodsExample.createCriteria().andNameLike("%" + goodsSearcherBo.getKeyword() + "%");
            goodsExample.setOrderByClause(goodsSearcherBo.getSort() + " " + goodsSearcherBo.getOrder());
            goodsList1 = goodsMapper.selectByExample(goodsExample);
        }else if(goodsSearcherBo.getCategoryId()!=null&&goodsSearcherBo.getBrandId()==null){
            goodsExample.clear();
            goodsExample.createCriteria().andBrandIdEqualTo(goodsSearcherBo.getCategoryId());
            goodsList1 = goodsMapper.selectByExample(goodsExample);
        }else {
            goodsExample.clear();
            goodsExample.createCriteria().andBrandIdEqualTo(goodsSearcherBo.getBrandId());
            goodsList1 = goodsMapper.selectByExample(goodsExample);

        }

        for (MarketGoods marketGoods : goodsList) {
            WxTopicGoodsDetailBo wxTopicGoodsDetailBo = new WxTopicGoodsDetailBo();
            //用beanUtils将参数多的信息赋值给少的
            BeanUtils.copyProperties(marketGoods, wxTopicGoodsDetailBo);
            //将对象假如到需要返回的数组中
            goodsDetailBos.add(wxTopicGoodsDetailBo);
        }
        //建立需要返回的二级目录的集合

        //根据商品id查询出所有商品所属的二级目录
        for (MarketGoods marketGoods : goodsList1) {
            //可能出现没有查询到的情况 那么就 TODO
            //查出二级目录  且需要不重复
            System.out.println(marketGoods.getCategoryId());
            MarketCategory category = categoryMapper.selectByPrimaryKey(marketGoods.getCategoryId());
            //如果为空,直接加入
            if (categoryList.isEmpty()) {
                categoryList.add(category);
            } else {
                int size = categoryList.size();
                int temp = 0;
                for (MarketCategory marketCategory : categoryList) {
                    //遍历当前集合,如果当前集!存在以有二级id,则不导入
                    if (marketCategory.getId().equals(marketGoods.getCategoryId())) {
                        break;
                    }
                    temp++;
                    if (temp == size) {
                        categoryList.add(category);
                        break;
                    }
                }
            }
        }
        PageInfo<MarketGoods> marketGoodsPageInfo = new PageInfo<>(goodsList);
        int pageNum = marketGoodsPageInfo.getPageNum();
        int pages = marketGoodsPageInfo.getPages();
        long total = marketGoodsPageInfo.getTotal();
        //给需要返回的Vo赋值
        wxSearchGoodsVo.setLimit(goodsSearcherBo.getLimit());
        wxSearchGoodsVo.setFilterCategoryList(categoryList);
        wxSearchGoodsVo.setList(goodsDetailBos);
        wxSearchGoodsVo.setPage(pageNum);
        wxSearchGoodsVo.setPages(pages);
        wxSearchGoodsVo.setTotal((int) total);
        wxSearchGoodsVo.setLimit(goodsSearcherBo.getLimit());
        return wxSearchGoodsVo;
    }

    /**
     * 关联商品展示
     *
     * @param id
     * @return
     */
    @Override
    public CommonData<MarketGoods> related(Integer id) {
        //分页
        int pageNum = 1;
        int pageSize = 6;
        PageHelper.startPage(pageNum, pageSize);
        //设置条件
        MarketGoodsExample example = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        //判空
        if (!ObjectUtils.isEmpty(id)) {
            criteria.andIdNotEqualTo(id);
        }
        //查询
        List<MarketGoods> marketGoods = goodsMapper.selectByExample(example);
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(marketGoods);
        return CommonData.data(pageInfo);
    }

    /**
     * 分类
     *
     * @param id
     * @return
     */
    @Override
    public WxCategoryDataVo category(Integer id) {
        //根据id查询当前category
        MarketCategory currentCategory = categoryMapper.selectByPrimaryKey(id);
        //封装返回值对象
        WxCategoryVo realCurrentCategory = new WxCategoryVo();
        BeanUtils.copyProperties(currentCategory, realCurrentCategory);
        //获取父id
        Integer pid = currentCategory.getPid();
        //查询条件配置
        MarketCategoryExample example = new MarketCategoryExample();
        MarketCategoryExample.Criteria criteria = example.createCriteria();
        criteria.andPidEqualTo(pid);
        //查询同一级的所有的类别
        List<MarketCategory> marketCategories = categoryMapper.selectByExample(example);
        //封装返回值需要的对象
        List<WxCategoryVo> brotherCategory = new ArrayList<>();
        for (MarketCategory marketCategory : marketCategories) {
            if (!ObjectUtils.isEmpty(marketCategory)) {
                WxCategoryVo wxCategoryVo = new WxCategoryVo();
                BeanUtils.copyProperties(marketCategory, wxCategoryVo);
                brotherCategory.add(wxCategoryVo);
            }
        }
        //查询父category
        MarketCategory marketCategory = null;
        if (pid != 0) {
            marketCategory = categoryMapper.selectByPrimaryKey(pid);
        }
        //封装返回值
        WxCategoryVo parentCategory = new WxCategoryVo();
        if (!ObjectUtils.isEmpty(marketCategory)) {
            BeanUtils.copyProperties(marketCategory, parentCategory);
        }
        WxCategoryDataVo dataVo = new WxCategoryDataVo();
        dataVo.setBrotherCategory(brotherCategory);
        dataVo.setCurrentCategory(realCurrentCategory);
        dataVo.setParentCategory(parentCategory);
        return dataVo;
    }


    /** 查询商品总数的信息，显示在分类界面上方的搜索框内
     * 查询商品总数的信息，显示在分类界面上方的搜索框内
     * @return com.cskaoyan.bean.vo.WxGoodsCountVo
     * @author landz
     * @create 2023/1/2 16:54
     */





    @Override
    public Integer getGoodsCount() {
        Integer wxGoodsCountVo = marketGoodsMapper.getGoodsCount();
        return wxGoodsCountVo;
    }
        //======================================================================================================================
        /*
         * 点击商品后出现商品所有的详细信息以及相关信息
         *
         * */
        @Autowired
        MarketCommentMapper commentMapper;
    @Autowired
    MarketGoodsAttributeMapper attributeMapper;
    @Autowired
    MarketIssueMapper issueMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketGoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    MarketSystemMapper systemMapper;
    @Autowired
    MarketBrandMapper brandMapper;
    @Autowired
    MarketFootprintMapper footprintMapper;
/*
* 商品细节id
* */
    @Override
    public WxGoodsDetailVo getGoodsDetailInfo(Integer id) {

        //会根据当前商品的id填入到历史记录中
        MarketFootprint marketFootprint = new MarketFootprint();
        marketFootprint.setGoodsId(id);
        marketFootprint.setDeleted(false);
        marketFootprint.setAddTime(new Date(System.currentTimeMillis()));
        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipal();
        marketFootprint.setUserId(principal.getId());
        footprintMapper.insertSelective(marketFootprint);
        //先根据商品的id查询出商品的详细信息
        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(id);

        //根据商品的id查询出当前商品的评价列表
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        //TODO

        //搜索评论的条件 valueid等于商品的id
        marketCommentExample.createCriteria().andValueIdEqualTo(marketGoods.getId()).andTypeEqualTo((byte)0);
        List<MarketComment> commentsList = commentMapper.selectByExample(marketCommentExample);
        int commentCount = commentsList.size();
        //创建要返回的评论列
        WxCommentBo wxCommentBo = new WxCommentBo(commentCount, commentsList);

        //根据goodsId查询attribute表里面的数据
        //创建查询条件
        MarketGoodsAttributeExample goodsAttributeExample = new MarketGoodsAttributeExample();
        goodsAttributeExample.createCriteria().andGoodsIdEqualTo(marketGoods.getId());
        //根据条件查询attribute表
        List<MarketGoodsAttribute> goodsAttributeList = attributeMapper.selectByExample(goodsAttributeExample);

        //查询issue表里面的数据  全部issue
        MarketIssueExample marketIssueExample = new MarketIssueExample();
        //查询全部的issue
        List<MarketIssue> marketIssueList = issueMapper.selectByExample(marketIssueExample);

        //根据商品id 查询productList表
        MarketGoodsProductExample productExample = new MarketGoodsProductExample();
        productExample.createCriteria().andGoodsIdEqualTo(marketGoods.getId());
        List<MarketGoodsProduct> productList = productMapper.selectByExample(productExample);

        //根据商品id查询brand信息
        MarketBrand marketBrand = brandMapper.selectByPrimaryKey(marketGoods.getBrandId());

        //创建要返回的WxGoodsSpecBo集合
        List<WxGoodsSpecificationBo> goodsSpecificationBoLinkedList = new LinkedList<>();
        //根据商品id查询所有的specification
        MarketGoodsSpecificationExample specificationExample = new MarketGoodsSpecificationExample();
        specificationExample.createCriteria().andGoodsIdEqualTo(marketGoods.getId());
        specificationExample.setOrderByClause("specification  desc");
        //得到排好序的商品表
        String temp=null;
        WxGoodsSpecificationBo goodsSpecificationBo=null;
        List<MarketGoodsSpecification> marketGoodsSpecificationList = goodsSpecificationMapper.selectByExample(specificationExample);
        LinkedList<WxGoodsSpecificationBo> wxGoodsSpecificationBos = new LinkedList<>();
        for (MarketGoodsSpecification marketGoodsSpecification : marketGoodsSpecificationList) {
            //遍历当前商品表将
            String specification=marketGoodsSpecification.getSpecification();
            if(!specification.equals(temp)){
                if (goodsSpecificationBo!=null){
                    wxGoodsSpecificationBos.add(goodsSpecificationBo);
                }
                goodsSpecificationBo = new WxGoodsSpecificationBo();
                goodsSpecificationBo.setName(specification);
                List<MarketGoodsSpecification> valueList = new LinkedList<>();
                valueList.add(marketGoodsSpecification);
                goodsSpecificationBo.setValueList(valueList);
                temp=specification;

            }else{
                List<MarketGoodsSpecification> valueList = goodsSpecificationBo.getValueList();
                valueList.add(marketGoodsSpecification);
            }
        }
        wxGoodsSpecificationBos.add(goodsSpecificationBo);

        //创建要返回的对象
        WxGoodsDetailVo wxGoodsDetailVo = new WxGoodsDetailVo();
        //给返回的对象的shareImage赋值
        wxGoodsDetailVo.setShareImage(marketGoods.getShareUrl());
        //收藏是否开启
        MarketSystemExample systemExample = new MarketSystemExample();
        systemExample.createCriteria().andKeyNameEqualTo("market_wx_share");
        List<MarketSystem> marketSystems = systemMapper.selectByExample(systemExample);
        String isOpen = marketSystems.get(0).getKeyValue();
        boolean flag;
        if (isOpen.equals("false")){
            flag=false;
        }else{
            flag=true;
        }
        //用户是否分享
        wxGoodsDetailVo.setShare(flag);
        //给返回对象的评论字段赋值
        wxGoodsDetailVo.setComment(wxCommentBo);
        //给返回对象的Attribute赋值
        wxGoodsDetailVo.setAttribute(goodsAttributeList);
        //给返回对象的GoodsInfo赋值
        wxGoodsDetailVo.setInfo(marketGoods);
        //给返回对象的issu赋值
        wxGoodsDetailVo.setIssue(marketIssueList);
        //给返回对象producList对象赋值
        wxGoodsDetailVo.setProductList(productList);
        //给brand属性赋值
        wxGoodsDetailVo.setBrand(marketBrand);
        wxGoodsDetailVo.setUserHasCollect(1);
        wxGoodsDetailVo.setSpecificationList(wxGoodsSpecificationBos);

        System.out.println(wxGoodsDetailVo);
        return wxGoodsDetailVo;
    }
}
